#!/usr/bin/env coffee

import {readFileSync, writeFileSync} from 'fs'
import {dirname, join} from 'path'
import walk from '@rmw/walk'
import thisdir from '@rmw/thisdir'


DIR = join(
  dirname thisdir(import.meta)
  'src'
)
console.log DIR

RE = /rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/

ColorToHex = (color) =>
  hexadecimal = (color-0).toString(16)
  if hexadecimal.length == 1 then '0' + hexadecimal else hexadecimal

tohex = (red, green, blue) =>
  '#' + ColorToHex(red) + ColorToHex(green) + ColorToHex(blue)

# console.log ConvertRGBtoHex(255, 100, 200)

rpl = (file) =>
  txt = readFileSync(file,'utf8').split('\n')

  write = false
  txt.map (line,n)=>
    pos = line.indexOf('rgb(')
    if pos + 1
      write = true
      txt[n] = line.replace(
        RE
        (m,g1,g2,g3)=>
          tohex(g1,g2,g3)
      )
  if write
    console.log file
    writeFileSync file,txt.join('\n')

do =>
  suffix = ('.'+i for i from 'vue styl'.split(' '))

  for await file from walk DIR
    for i in suffix
      if file.endsWith i
        await rpl file
        console.log file
        break
